package cn.fl.settlement.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.settle.dto.PaySchMSettleDTO;
import cn.fl.settlement.service.ISettleBillService;
import cn.fl.system.constant.SysLogConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
* @Description:    结清业务控制层new
* @Author:         liurong
* @CreateDate:     2020/11/24 15:29
* @Version:        1.0
*/
@Controller
@RequestMapping("/settlement/bill")
public class SettleBillController extends BaseController {

    @Autowired
    private ISettleBillService settleBillService;

    /**
     * 到结清选择期次页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/chooseSettlePd.do", method = {RequestMethod.GET})
    public ModelAndView chooseSettlePd(HttpServletRequest request) {
        // 支付表ID
        String paySchIdStr = request.getParameter("id");
        ModelAndView modelAndView = new ModelAndView("settlement/common/settleChoosePd");
        try {
            if (StringUtils.isEmpty(paySchIdStr)) {
                throw new BaseException("结清支付表ID不能为空！");
            }

            // call the interface
            settleBillService.getSettlePdIfCheckPass(Long.parseLong(paySchIdStr), modelAndView);

        } catch (BaseException e) {
            BaseLogUtils.newLogger("操作人{0},支付表{1}校验结清规则并获取结清期次数据业务异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            modelAndView.addObject("error", 1);
            modelAndView.addObject("errorMsg", e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.newLogger("操作人{0},支付表{1}校验结清规则并获取结清期次数据系统异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
        return modelAndView;
    }

    /**
     * 预览结清数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/preview.do", method = {RequestMethod.GET})
    public ModelAndView preview(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("settlement/common/settlePreviewPage");
        String paySchIdStr = request.getParameter("paySchId");
        String settlePdStr = request.getParameter("settlePd");
        try {
            if (StringUtils.isEmpty(paySchIdStr)) {
                throw new BaseException("结清支付表ID不能为空！");
            }
            if (StringUtils.isEmpty(settlePdStr)) {
                throw new BaseException("结清期次不能为空！");
            }

            settleBillService.getSettleDataPreview(Long.parseLong(paySchIdStr), Integer.parseInt(settlePdStr), view);
        } catch (BaseException e) {
            BaseLogUtils.newLogger("操作人{0},跳转支付表{1}结清预览页面业务异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("操作人{0},跳转支付表{1}结清预览页面系统异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
        return view;
    }

    /**
     * 发起结清流程
     * @param request
     * @return
     */
    @RequestMapping(value = "/startFlow.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object startFlow(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);

        String paySchIdStr = request.getParameter("paySchId");
        String settlePdStr = request.getParameter("settlePd");
        try {
            if (StringUtils.isEmpty(paySchIdStr)) {
                throw new BaseException("结清支付表ID不能为空！");
            }
            if (StringUtils.isEmpty(settlePdStr)) {
                throw new BaseException("结清期次不能为空！");
            }

            settleBillService.startFlow(Long.parseLong(paySchIdStr), Integer.parseInt(settlePdStr));
        } catch (BaseException e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL + e.getMessage());
            BaseLogUtils.newLogger("操作人{0},支付表{1}发起结清流程业务异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + e.getMessage());
            BaseLogUtils.newLogger("操作人{0},支付表{1}发起结清流程系统异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
        }
        return result;
    }

    /**
     * 查询流程发起结果
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryStartResult.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object queryStartResult(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);

        String paySchIdStr = request.getParameter("paySchId");
        try {
            if (StringUtils.isEmpty(paySchIdStr)) {
                throw new BaseException("结清支付表ID不能为空！");
            }
            String procNo = settleBillService.querySettleStartResult(Long.parseLong(paySchIdStr));
            if (StringUtils.isNotEmpty(procNo)) {
                result.setInfo("流程发起成功！流程编号：" + procNo);
                result.setData(1);
            } else {
                result.setData(0);
                result.setInfo("流程发起中，请稍后查看。");
            }
        } catch (BaseException e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL + e.getMessage());
            BaseLogUtils.newLogger("操作人{0},支付表{1}查询发起结清流程结果业务异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + e.getMessage());
            BaseLogUtils.newLogger("操作人{0},支付表{1}查询发起结清流程结果系统异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
        }
        return result;
    }


    /**
     * 流程附加页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toAuditPage.do", method = {RequestMethod.GET})
    public ModelAndView toAuditPage(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("settlement/common/settleAuditPage");
        // 流程实例ID，必须
        String processInstanceId = request.getParameter("processInstanceId");
        /*
            request中的参数：
             ckControl：控制"维护结清费用项"按钮
             fileAuth：上传附加控制参数：1-上传10；2-上传20,30,40；3-上传10,20,30,40
             confirm：确认我司付款账户

             收付款账户控制参数：
             showBk_oCIn：控制显示客户付款，我司收款：1-显示
             showBk_oCOut：控制显示客户收款，我司付款：1-显示
             isDetail_bk：控制客户付款，我司收款是否只读：1-只读
             editInto：控制编辑客户收款：1-可编辑
             editOut：控制编辑我司付款：1-可编辑

             开票模块控制参数：
             optba：标识是否需要开票新增列表页面
             optbf：标识是否显示财务开票列表页面
             optbd：是否显示开票详细列表页面
         */
        try {
            if (StringUtils.isEmpty(processInstanceId)) {
                throw new BaseException("流程实例ID不能为空！");
            }
            // 循环request中的参数传到页面
            Enumeration enu = request.getParameterNames();
            while (enu.hasMoreElements()) {
                String paraName = (String) enu.nextElement();
                view.addObject(paraName, request.getParameter(paraName));
            }
            // 调用接口
            PaySchMSettleDTO settleDataFlow = settleBillService.getSettleDataFlow(processInstanceId, view);
            view.addObject("paySchId", settleDataFlow.getPaySchId());
            return view;
        } catch (BaseException e) {
            BaseLogUtils.newLogger("操作人{0},查看流程实例ID{1}结清审核页面业务异常：", CurrentThreadContext.getCurrentUserName(), processInstanceId).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("操作人{0},查看流程实例ID{1}结清审核页面系统异常：", CurrentThreadContext.getCurrentUserName(), processInstanceId).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
            throw e;
        }
    }

    /**
     * 刷新结清款
     * @param request
     * @return
     */
    @RequestMapping(value = "/refreshSettleAmt.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object refreshSettleAmt(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_SYNC_SUCC);

        String paySchIdStr = request.getParameter("paySchId");
        try {
            if (StringUtils.isEmpty(paySchIdStr)) {
                throw new BaseException("结清支付表ID不能为空！");
            }
            Double settleAmt = settleBillService.refreshSettleAmt(Long.parseLong(paySchIdStr));
            if (settleAmt != null) {
                result.setData(settleAmt);
            } else {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("刷新结清款失败！");
            }
        } catch (BaseException e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("刷新结清款失败！" + e.getMessage());
            BaseLogUtils.newLogger("操作人{0},支付表{1}查询结清金额业务异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("刷新结清款失败！" + e.getMessage());
            BaseLogUtils.newLogger("操作人{0},支付表{1}查询结清金额系统异常：", CurrentThreadContext.getCurrentUserName(), paySchIdStr).setThrowable(e).error(LogExceptionEnum.API_CODE_0102);
        }
        return result;
    }

}

